import React, { useState } from "react";
import { Modal, Form, Upload, Button } from "antd";
import { modalPropsType } from "@/constants/types";
import { fileUpload } from "@/services/common";
import { RcFile, UploadProps } from "antd/lib/upload";
import type { UploadFile } from 'antd/es/upload/interface';
import { UploadOutlined } from "@ant-design/icons";

const {Item} = Form;
const rules = [{required: true, message: '此项必填'}];

const ContractUpload = ({title, onCancel, onSubmit, visible, loading, currentRow}: modalPropsType) => {
  const [form] = Form.useForm();
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [previewTitle, setPreviewTitle] = useState('');
  const [fileList, setFileList] = useState<UploadFile[]>([]);

  const handleSubumit = async () => {
    const res = await form.validateFields();
    onSubmit({
      contractFileUrl: res?.fileUrl?.[0]?.response,
      contractFileName: res?.fileUrl?.[0]?.response?.split('/')?.[1],
      customerId: currentRow?.id
    });
  }

  const normFile = (e: any) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e?.fileList;
  };

  const getBase64 = (file: RcFile): Promise<string> =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = (error) => reject(error);
  });

  const handlePreview = async (file: UploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj as RcFile);
    }

    setPreviewImage(file.url || (file.preview as string));
    setPreviewOpen(true);
    setPreviewTitle(file.name || file.url!.substring(file.url!.lastIndexOf('/') + 1));
  };

  const uploadFileReq = ({file, filename, onSuccess, onError, data = {}}: any) => {
    const formData = new FormData();
    formData.append(filename, file);
    Object.keys(data).forEach(key => {
      formData.append(key, data?.[key]);
    })
    fileUpload(formData).then(
      res => {
        if (res?.code === '0') {
          onSuccess(res?.data);
        } else {
          onError(res?.data)
        }
      }
    )
  }

  const handleChange: UploadProps['onChange'] = ({ fileList: newFileList }) => setFileList(newFileList);
  const handleCancel = () => setPreviewOpen(false);

  return (
    <>
      <Modal
        open={visible}
        title={title}
        confirmLoading={loading}
        onCancel={onCancel}
        onOk={handleSubumit}
      >
        <Form form={form} className="modal-form-padding">
          <Item label="上传合同" name="fileUrl" valuePropName="fileList" getValueFromEvent={normFile} rules={rules}>
              <Upload 
                maxCount={1} 
                customRequest={uploadFileReq}
                onPreview={handlePreview}
                onChange={handleChange}
                // beforeUpload={() => false}
                fileList={fileList}
                data={{businessCode: 'contracts'}} 
              >
                <Button style={{width: 200, height: 30}} icon={<UploadOutlined />}>点击上传</Button>
              </Upload>
            </Item>
        </Form>
      </Modal>
      <Modal open={previewOpen} title={previewTitle} footer={null} onCancel={handleCancel}>
        <img alt="example" style={{ width: '100%' }} src={previewImage} />
      </Modal>
    </>
  );
}
export default ContractUpload;